package com.zk.controller;

import com.alibaba.fastjson.JSONObject;
import com.zk.entity.SysUser;
import com.zk.service.SysUserService;
import com.zk.util.DateUtil;
import com.zk.vcode.Captcha;
import com.zk.vcode.GifCaptcha;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.*;
import javax.validation.Valid;
import java.util.Map;

/**
 * Created by zhengkai on 2017/2/23.
 */
@Controller
public class LoginController {
    @Autowired
    private SysUserService userService;

    @RequestMapping(value = "/index")
    public String index(ModelMap modelMap){
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        modelMap.put("name",user.getNickname());
        return "index";
    }

    @RequestMapping(value = {"/","/login"})
    public String login(){
        if(SecurityUtils.getSubject().isAuthenticated())
            return "redirect:/index";
        return "login";
    }

    @RequestMapping(value = "/signup")
    public String signup(){
        return "signup";
    }

    @RequestMapping(value = "/signupUser",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> signupUser(@Valid SysUser user){
        JSONObject resultMap = new JSONObject();
        user.setCreateTime(DateUtil.getCurrentDateTime());
        user.setStatus(1L);
        user.setPswd(new Md5Hash(new Md5Hash(user.getPswd(), user.getNickname())).toString());
        user.setSalt(user.getNickname());
        Boolean result = userService.insert(user);
        if(result){
            resultMap.put("status",200);
        }
        return resultMap;
    }

    @RequestMapping(value = "/403")
    public String noPermission(){
        return "403";
    }

    /**
     * ajax登录请求
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value="ajaxLogin",method= RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> submitLogin(HttpServletRequest request, String username, String password, String vcode, Boolean rememberMe) {
        JSONObject resultMap = new JSONObject();
        if(vcode==null||vcode==""){
            resultMap.put("status", 500);
            resultMap.put("message", "验证码不能为空！");
            return resultMap;
        }

        Session session = SecurityUtils.getSubject().getSession();
        //转化成小写字母
        vcode = vcode.toLowerCase();
        String v = (String) session.getAttribute("_code");
        //还可以读取一次后把验证码清空，这样每次登录都必须获取验证码
        //session.removeAttribute("_come");
        if(!vcode.equals(v)){
            resultMap.put("status", 500);
            resultMap.put("message", "验证码错误！");
            return resultMap;
        }

        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
            SecurityUtils.getSubject().login(token);
            resultMap.put("status", 200);
            resultMap.put("message", "登录成功");
        }catch (IncorrectCredentialsException e1){
            resultMap.put("message", "帐号或密码不正确！");
        }catch(ExcessiveAttemptsException e2){
            resultMap.put("message", "登录次数过多，请稍后重试！");
        }
        catch (Exception e) {
            resultMap.put("status", 500);
            resultMap.put("message", "登录失败");
        }
        return resultMap;
    }

    /**
     * 获取验证码（Gif版本）
     * @param response
     */
    @RequestMapping(value="getGifCode",method=RequestMethod.GET)
    public void getGifCode(HttpServletResponse response, HttpServletRequest request){
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/gif");
            /**
             * gif格式动画验证码
             * 宽，高，位数。
             */
            Captcha captcha = new GifCaptcha(146,33,4);
            //输出
            captcha.out(response.getOutputStream());
            HttpSession session = request.getSession(true);
            //存入Session
            session.setAttribute("_code",captcha.text().toLowerCase());
        } catch (Exception e) {
            System.err.println("获取验证码异常："+e.getMessage());
        }
    }
}
